package cn.lkp.mall.member.service.impl;

import cn.lkp.common.utils.HttpUtils;
import cn.lkp.mall.member.dao.MemberLevelDao;
import cn.lkp.mall.member.entity.MemberLevelEntity;
import cn.lkp.mall.member.exception.PhoneExitException;
import cn.lkp.mall.member.exception.UsernameExitException;
import cn.lkp.mall.member.vo.MemberLoginVo;
import cn.lkp.mall.member.vo.MemberRegisterVo;
import cn.lkp.mall.member.vo.SocialUser;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.lkp.common.utils.PageUtils;
import cn.lkp.common.utils.Query;

import cn.lkp.mall.member.dao.MemberDao;
import cn.lkp.mall.member.entity.MemberEntity;
import cn.lkp.mall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    MemberLevelDao memberLevelDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberRegisterVo vo) {
        MemberEntity memberEntity = new MemberEntity();
        //设置会员默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());
        //检查用户名或者手机号是否唯一,为了让controller感知到异常，使用异常机制
        checkUsernameUnique(vo.getUsername());
        checkPhoneUnique(vo.getPhone());
        //设置用户名和手机号
        memberEntity.setUsername(vo.getUsername());
        memberEntity.setMobile(vo.getPhone());
        //设置用户名同时是昵称名，以便登陆成功后在页面显示昵称
        memberEntity.setNickname(vo.getUsername());
        //密码加密后存储
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);

        baseMapper.insert(memberEntity);
    }

    public void checkUsernameUnique(String username) throws UsernameExitException{
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if(count>0){
            throw new UsernameExitException();
        }
    }

    public void checkPhoneUnique(String phone) throws PhoneExitException{
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if(count>0){
            throw new PhoneExitException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        //去数据库查询
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", vo.getLoginacct()).or().eq("mobile", vo.getLoginacct()));
        if(memberEntity==null){
            return null;
        }else {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            boolean matches = encoder.matches(vo.getPassword(), memberEntity.getPassword());
            if(matches){
                return memberEntity;
            }else{
                return null;
            }
        }
    }

    @Override
    public MemberEntity oauthLogin(SocialUser vo) throws Exception {
        //先查数据中是否有社交账号唯一标识social_uid的记录
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", vo.getUid()));
        if(memberEntity!=null){
            //数据中有记录，创建更新实体类
            MemberEntity update = new MemberEntity();
            //查找ums_member表中社交账号唯一标识social_uid对应的id并赋值
            update.setId(memberEntity.getId());
            //更新access_token和expires_in
            update.setAccessToken(vo.getAccess_token());
            update.setExpiresIn(vo.getExpires_in());
            //传入更新实体类
            baseMapper.updateById(update);
            //返回登陆信息
            memberEntity.setAccessToken(vo.getAccess_token());
            memberEntity.setExpiresIn(vo.getExpires_in());
            return memberEntity;
        }else{
            //数据中没有记录，进行注册
            MemberEntity register = new MemberEntity();
            //以下网络操作放在try catch语句中
            try{
                //查询当前社交账户的信息
                Map<String,String> query = new HashMap<>();
                query.put("access_token",vo.getAccess_token());
                query.put("uid",vo.getUid());
                //TODO path的信息待查
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json",
                        "get", new HashMap<>(), query);
                if(response.getStatusLine().getStatusCode()==200){
                    String json = EntityUtils.toString(response.getEntity());
                    //转成JSON Object
                    JSONObject jsonObject = JSON.parseObject(json);
                    //获取社交账号的名称
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    //设置社交账号名称为登陆用户的昵称、性别...
                    register.setNickname(name);
                    register.setGender("m".equals(gender)?1:0);

                }
            }
            catch(Exception e){
            }
            //插入这条记录前，必须关联社交账号和用户登陆信息，放在try...catch语句外面，即使try操作失败，也能被执行。
            register.setSocialUid(vo.getUid());
            register.setAccessToken(vo.getAccess_token());
            register.setExpiresIn(vo.getExpires_in());
            //插入这条记录
            baseMapper.insert(register);
            return register;
        }
    }
}